package com.weishenai.Servlet;

import cn.hutool.Hutool;
import cn.hutool.json.JSONUtil;
import com.weishenai.Entity.User;
import com.weishenai.Service.UserService;
import com.weishenai.Service.impl.UserServiceImpl;
import com.weishenai.Utils.Constants;
import com.weishenai.Utils.TokenUtil;
import com.weishenai.common.Result;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Auther: weishenai
 * @Date: 2021/10/04/17:07
 * @Description:
 */
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("userName");
        String password = req.getParameter("passWord");
        TokenUtil tokenUtil = new TokenUtil();
        Result result = null;
        UserService userService = new UserServiceImpl();
        User user = userService.login(username);
        if (user == null) {
            result = Result.error("-1", "没有此用户");
        } else {
            if (user.getPassword().equals(password)) {
                req.getSession().setAttribute(Constants.USER_SESSION, user);
                result = Result.success(tokenUtil.creatToken(user.getName()));
            } else {
                result = Result.error("-1", "用户或密码错误");
            }
        }
        resp.setHeader("content-type", "text/html;charset=UTF-8");
        PrintWriter out = resp.getWriter();

        out.println(JSONUtil.toJsonStr(result));
        out.flush();
        out.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
